package com.example.web;

import com.example.Util.JwtUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Enumeration;

@Component
public class AuthFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext context = RequestContext.getCurrentContext();
        String path = context.getRequest().getServletPath();
        if("/user/iflogin".equals(path)  ){
            return true;
        }

        return false;
    }


    @Autowired
    StringRedisTemplate redisTemplate;
    @Override
    public Object run() throws ZuulException {

        RequestContext rc = RequestContext.getCurrentContext();
        //获取令牌
        String jwt = (String) redisTemplate.opsForValue().get("jwt") ;
        // axios.get('xxxx',{ headers:{Authorization:jwt}})
        // 思考: 超链接请求, 怎么获取 jwt: cookie + 请求参数


        //验证jwt
        if(jwt == null){
            response(null);

            return null;
        }

        try {

            Claims claims = JwtUtil.parseJWT(jwt);

            Object userId =   claims.get("userId");

            rc.addZuulRequestHeader("userId", userId.toString());



        }
        catch (Exception e){
            response(null);
        }
        


        return null;
    }

    private void response(String s) {
        RequestContext rc = RequestContext.getCurrentContext();
        //阻止请求访问 目标资源
        rc.setSendZuulResponse(false);
        rc.setResponseBody(s);

    }
}
